﻿using Ipmce.RemoteVoting.Common.Tools.CardReader.Exceptions;
using Ipmce.RemoteVoting.Common.Tools.CardReader.Utils;
using Subsembly.SmartCard;

namespace Ipmce.RemoteVoting.Common.Tools.CardReader
{
	public class PassportReaderFacade : IPassportReader
	{
        private readonly ICardTerminalFactory _cardTerminalFactory = new CardTerminalFactory();

		public byte[] GetRawDg2Data(string mrz)
		{
		    var activeTerminalNames = _cardTerminalFactory.GetActiveTerminalNames();
		    if (activeTerminalNames.Count == 0)
		    {
		        throw new PassportNotFoundException("Unable to find active card readers");
		    }
		    foreach (var activeTerminalName in activeTerminalNames)
		    {
		        try
		        {
		            using (var reader = new PassportReaderImpl(new CardPcScTerminal(activeTerminalName)))
		            {
		                return reader.GetRawDg2Data(mrz);
		            }
		        }
                catch (CardReaderException)
		        {
		        }
		    }
            throw new PassportNotFoundException("Unable to communicate with any active card readers");
		}
	}
}